import { NextRequest, NextResponse } from 'next/server';
import { DataMigrationScript } from '../../../scripts/migrate-to-independent-tables';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action } = body; // 'migrate', 'validate', 'rollback'

    const migration = new DataMigrationScript();

    switch (action) {
      case 'migrate':
        console.log('开始执行数据迁移...');
        await migration.migrate();
        
        console.log('验证迁移结果...');
        const isValid = await migration.validateMigration();
        
        migration.cleanup();
        
        if (isValid) {
          return NextResponse.json({
            success: true,
            message: '数据迁移成功完成并通过验证',
            timestamp: new Date().toISOString()
          });
        } else {
          return NextResponse.json({
            success: false,
            message: '数据迁移完成但验证失败',
            timestamp: new Date().toISOString()
          }, { status: 500 });
        }

      case 'validate':
        console.log('验证迁移结果...');
        const validationResult = await migration.validateMigration();
        migration.cleanup();
        
        return NextResponse.json({
          success: validationResult,
          message: validationResult ? '验证通过' : '验证失败',
          timestamp: new Date().toISOString()
        });

      default:
        return NextResponse.json({
          error: '无效的操作类型',
          validActions: ['migrate', 'validate']
        }, { status: 400 });
    }

  } catch (error) {
    console.error('迁移操作失败:', error);
    return NextResponse.json({
      success: false,
      error: '迁移操作失败',
      details: error instanceof Error ? error.message : String(error),
      timestamp: new Date().toISOString()
    }, { status: 500 });
  }
}

export async function GET(request: NextRequest) {
  try {
    // 返回迁移状态信息
    return NextResponse.json({
      success: true,
      message: '独立表迁移API',
      availableActions: [
        {
          action: 'migrate',
          description: '执行完整的数据迁移并验证',
          method: 'POST',
          body: { action: 'migrate' }
        },
        {
          action: 'validate',
          description: '验证迁移结果',
          method: 'POST',
          body: { action: 'validate' }
        }
      ],
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('获取迁移信息失败:', error);
    return NextResponse.json({
      error: '获取迁移信息失败',
      details: error instanceof Error ? error.message : String(error)
    }, { status: 500 });
  }
}
